﻿using System;
using UnityEngine;

public class EventTransparentObject {
	// === Public =====================================================================================================
	public static void Action() {
		var baseData = MapEditorBaseData.GetInstance;
		if (!baseData.HasCamera() || !baseData.HasTransparentObject()) {
			return;
		}
		var camera = baseData.Camera.camera;
		var transparentObjectElement = baseData.TransparentObject;
		var viewPort = camera.ScreenToViewportPoint(Input.mousePosition);
		var pos = camera.ViewportToWorldPoint(NormalizeViewPort(viewPort));
		pos.y = transparentObjectElement.ElementModel.Position.y;
		var point = NormalizePoint(pos);
		transparentObjectElement.SetPosition(point);
	}

	// === Private ====================================================================================================
	private static Vector3 NormalizeViewPort(Vector3 viewPort) {
		return new Vector3 {
			x = Port(viewPort.x),
			y = Port(viewPort.y),
			z = viewPort.z
		};
	}

	private static float Port(float viewPort) {
		if (viewPort < 0) {
			return 0;
		}
		return viewPort > 1 ? 1 : viewPort;
	}

	private static Vector3 NormalizePoint(Vector3 position) {
		return new Vector3 {
			x = Point(position.x),
			y = position.y,
			z = Point(position.z)
		};
	}

	private static int Point(float position) {
		var point = (int)position;
		if (!(Math.Abs(position) - Math.Abs(point) > .5f)) {
			return point;
		}
		if (position < 0) {
			return point - 1;
		}
		return point + 1;
	}
}